package com.temp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.temp.dto.SearchUserDTO;
import com.temp.entity.Role;
import com.temp.entity.User;
import com.temp.mapper.RoleMapper;
import com.temp.mapper.UserMapper;
import com.temp.service.UserService;
import com.temp.vo.CampaignDetailVO;
import com.temp.vo.CustomPageVO;
import com.temp.vo.UserDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveUser(User user, String roleName) {
        Role role = roleMapper.selectOne(Wrappers.<Role>lambdaQuery().eq(Role::getName, roleName));
        user.setRoleId(role.getId());
        return userMapper.insert(user) > 0;
    }

    @Override
    public User findByUsername(String username) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,username);
        return userMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public User findByEmail(String email) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getEmail,email);
        return userMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public boolean checkLoginNameUnique(String name) { return findByUsername(name) == null; }

    @Override
    public boolean checkEmailUnique(String email) {
        return findByEmail(email) == null;
    }

    @Override
    public CustomPageVO<UserDetailVO> findAllUserDetail(SearchUserDTO userDTO) {
        CustomPageVO<UserDetailVO> customPageVO = new CustomPageVO<>();
        Integer count = Optional.ofNullable(userMapper.countAllUserDetail(userDTO)).orElse(0);
        customPageVO.setTotal(count);
        if(count < 1) {
            customPageVO.setDataList(Collections.emptyList());
            return customPageVO;
        }
        List<UserDetailVO> userDetail = userMapper.findAllUserDetail(userDTO);
        customPageVO.setDataList(userDetail);
        return customPageVO;
    }

    @Override
    public List<User> selectRandomRobots(int limit) {
        return userMapper.selectRandomRobots(limit);
    }

    @Override
    public void updateUserBalance(Long userId, BigDecimal amount) {
        userMapper.updateUserBalance(userId, amount);
    }
}
